package mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

public class Mail {

	private String inPathFile = "/home/lutecia/Desktop/test.eml";
	private String outPath = "/home/lutecia/Desktop/";

	public void mainTEST(String args[]) throws Exception {
		File emlFile = new File(inPathFile);

		InputStream source = new FileInputStream(emlFile);

		Properties props = System.getProperties();
		props.put("mail.host", "smtp.dummydomain.com");
		props.put("mail.transport.protocol", "smtp");

		Session mailSession = Session.getDefaultInstance(props, null);
		MimeMessage message = new MimeMessage(mailSession, source);
		Multipart multipart = (Multipart) message.getContent();
		getAttachments(multipart);
	}

	public void getAttachments(Multipart multipart) throws MessagingException,
			FileNotFoundException, IOException {
		for (int x = 0; x < multipart.getCount(); x++) {
			BodyPart bodyPart = multipart.getBodyPart(x);
			String disposition = bodyPart.getDisposition();
			if (disposition == null) {
				getAttachments((Multipart) bodyPart.getContent());
			} else {
				if (disposition.equals(BodyPart.ATTACHMENT)) {
					DataHandler handler = bodyPart.getDataHandler();
					String fileName = handler.getName();
					File file = new File(outPath + fileName);
					FileOutputStream fos = new FileOutputStream(file);
					handler.writeTo(fos);
				}
			}
		}
	}
}
